<template>
  <div class="d-flex align-items-stretch h-250px">
    <span
      class="h2 d-flex flex-column justify-content-center align-items-center"
      style="writing-mode: vertical-rl; text-orientation: mixed; min-width: 48px"
    >
      {{ props.selectedRepo.name }}
    </span>
    <div class="flex-grow-1">
      <apexchart
        ref="chartRef"
        type="bar"
        height="300"
        :options="chartOptions"
        :series="series"
      ></apexchart>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { statisticsService } from '@/services/analysis/statistics.service';

const props = defineProps({
  selectedRepo: {
    type: Object,
    required: true,
  },
});

const chartOptions = ref({
  chart: { id: 'repo-monthly-stats' },
  xaxis: {
    categories: [],
  },
  yaxis: [{ title: { text: '提交' } }, { opposite: true, title: { text: '代码' } }],
});
const series = ref([
  { name: '提交', data: [] },
  { name: '代码', data: [] },
]);

const chartRef = ref(null);

watch(
  () => props.selectedRepo,
  async (newRepo) => {
    if (newRepo) {
      try {
        const data = await statisticsService.getRepoMonthlyStats(
          newRepo.gitInstance,
          newRepo.repoId,
        );
        const months = data.map((item) => item.month);
        const commits = data.map((item) => item.commitCount);
        const changes = data.map((item) => item.totalChanges);

        chartRef.value.updateOptions({
          xaxis: {
            categories: months,
          },
        });
        series.value[0].data = commits;
        series.value[1].data = changes;
      } catch (error) {
        console.error('Error fetching monthly stats:', error);
      }
    }
  },
  { immediate: true },
);
</script>
